package com.fengke.util.master_slave;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

import com.fengke.util.LoggerFactory;

public class DataSourceAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {
	private Logger logger = LoggerFactory.getLogger(DataSourceAdvice.class);
	private long beginTime = 0;
	
	public void before(Method method, Object[] arg, Object target) throws Throwable {
		logger.debug("开始业务处理[" + method.getName() + "];全路径[" + target.getClass().getName() + "]");
		beginTime = System.currentTimeMillis();
		if (method.getName().startsWith("add")
				|| method.getName().startsWith("create")
				|| method.getName().startsWith("del")
				|| method.getName().startsWith("edit")
				|| method.getName().startsWith("insert")
				|| method.getName().startsWith("save")
				|| method.getName().startsWith("update")
				|| method.getName().startsWith("modeify")) {
			logger.debug(method.getName() + "数据源切换到:master");
			DataSourceSwitch.setMaster();
		} else {
			logger.debug(method.getName() + " 数据源切换到:slave");
			DataSourceSwitch.setSlave();
		}
	}

	public void afterReturning(Object arg, Method method, Object[] args, Object target) throws Throwable {
		logger.debug("结束业务处理[" + method.getName() + "];耗时:" + (System.currentTimeMillis() - beginTime) + "毫秒;全路径[" + target.getClass().getName() + "]");
	}

	public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
		DataSourceSwitch.setSlave();
		logger.error((method == null ? "" : method.getName()) + "数据源调用异常信息:" + ex.getMessage());
	}

}
